$(function(){
	  var base="http://open.yonyoutelecom.cn/";//正式环境
//	  var base="http://opentest.yonyoutelecom.cn:8090/";//沙箱环境
//	  var base="http://172.20.8.236:8080/";//测试环境
	  sessionStorage.setItem("base", base); 
	  var resourceType={
		min:'分钟',
		ite:'条',
		ome:'兆',
		pem:'人月'
	  },originalType={
	    BUY:'购买',
	    GIV:'赠送'
	  };
	  
	  var telephoneElem=$('#telephone'),loadPrompt,
	  paramJSON=utils.createQueryStringJSONObject(location.search.substr(1),true);
	  
	  function queryAndUpdateAccoutInfo(){
		    $.ajax({
			      type : "get",
		          dataType : "jsonp",
			      url : base+"orgacc/qryOrgAccInfo.do",
			      data : paramJSON,
			      success:function(data){
			    	  console.log('qryOrgAccInfo=='+JSON.stringify(data));
			    	  if(data.result==='0'){
		    			    $.ajax({
		    				      type : "get",
		    			          dataType : "jsonp",
		    				      url : base+"orgacc/updOrgAccByReleCode.do",
		    				      data : $.extend(paramJSON,{
		    				    	  authData:{
		    				    		  ext_orgName:data.data.ext_orgName,
		    				    		  ext_orgLinker:data.data.ext_orgLinker,
		    				    		  ext_orgEmail:data.data.ext_orgEmail
		    				    	  },
		    				    	  h5Demo_code:'dudu'
		    				      }),
		    				      success:function(data){
		    				    	  console.log('updOrgAccByReleCode=='+JSON.stringify(data));
		    				    	  if(data.result==='0'){
		    				    		  sessionStorage.setItem('parameter',JSON.stringify(paramJSON));
		    				              location.assign('success.html?message=账号更新操作成功&title=账号更新'); 
		    				    	  }else{
		    						     new UserPrompt(data.discripe||data.describe);
		    				    	  }    	  
		    				      },
		    				      error:function(data){
		    				    	  if(data&&data.describe)
		    					        new UserPrompt(data.describe);
		    				      }
		    				    });	  
			    	  }else{
					        new UserPrompt(data.discripe||data.describe);
			    	  }    	  
			      },
			      error:function(data){
			    	  if(data&&data.describe)
				        new UserPrompt(data.describe);
			      }
			    });
	  }
	  
	  function accountPrompt(){
			$(document.body).on('click','#save',function(){
   				if(loadPrompt)
    				  loadPrompt.close();
    				loadPrompt=null;
				queryAndUpdateAccoutInfo();
			});
			$(document.body).on('click','#cancel',function(){
				if(loadPrompt)
				  loadPrompt.close();
				loadPrompt=null;
			});
			loadPrompt=new LoadPrompt([{
					id:'mask',
					closed:false
				},{
    				id:'alert_tip',
    				html:'<p>暂无可合并的账号信息，保存或取消</p><div class="btn" ><span class="bordeR" id="save">保存</span><span id="cancel">取消</span></div>'
				}]);
	  }
	  
	  function transformCache(rs){
		  var data=[],elem,custAccount,appData;
		  for (var i = 0; i < rs.length; i++) {
			custAccount=rs[i];
			elem={
			  name:decodeURI(custAccount.ext_orgName),
			  cust_account:custAccount.cust_account,
			  account_balance:custAccount.credit_balance+'元',
			  resources:[]
			};
			for (var m = 0; m < custAccount.appdata.length; m++) {
				appData=custAccount.appdata[m];			
				for (var k = 0; k < appData.resources.length; k++) {
					var rs0=appData.resources[k];
					$.extend(rs0,{
						product_name:decodeURI(rs0.product_name),
						balance:rs0.resuource_num+resourceType[rs0.measure_type],
						resource_type:originalType[rs0.buy_type],
						appName:decodeURI(appData.app_name)
					})
				}
				Array.prototype.push.apply(elem.resources,appData.resources);
			}
			data.push(elem);
		}
		sessionStorage.setItem('correlationaccount',JSON.stringify(data));    		  
	  }
	  
	  function containsCurrentApp(rs,cust_account){
		  if(rs.length>1)
			 return false;
		  else if(rs.length===1){
			  var cust=rs[0];
			  if(cust.cust_account===cust_account)
				  return true;
			  else
				  return false;
		  }else
			  return false;
	  }
	  
	
	  var smscode=$('#smscode'),
	  submitBtn=$('#unified_ok').on('click',function(){
		var captcha=smscode.val(),
		telephone = telephoneElem.val(),
		unionCode=$('#code').val(),
		result;
		if(telephone===''){//未输入手机号
	    	new UserPrompt('请输入手机号码');
            return;
		}
	    result=utils.checkTelephoneNumber(telephone);
	    if (!result.success) {//手机号校验未通过
	    	new UserPrompt(result.msg);
	        return;
	    }
		if(unionCode===''){//未输入关联码
	    	new UserPrompt('请输入关联码');
	        return;
		}
		if(captcha===''){//未输入验证码
	    	new UserPrompt('请输入验证码');
	        return;
		}
		if(captcha.length!==6){//验证码为6位数字
	    	new UserPrompt('请输入正确的验证码');
			return;
		}
	    $.ajax({
		      type : "get",
	          dataType : "jsonp",
		      url : base+"orgacc/qryMergeableOrgListByCust.do",
		      data : $.extend(paramJSON,{
		    	  verifyCode:captcha,
		    	  ext_orgReleCode:unionCode,
		    	  ext_orgPhone:telephone
		      }),
		      success:function(data){
		    	  console.log('qryMergeableOrgListByCust=='+JSON.stringify(data));
		    	  if(data.result==='0'){
		    		  if(data.status==='0001'){//存在可合并账户，进行查询并更新操作
		    			  if(containsCurrentApp(data.data,paramJSON.cust_account)){
		    				  accountPrompt();
		    				  return;
		    			  }
		    			    $.ajax({
		    				      type : "get",
		    			          dataType : "jsonp",
		    				      url : base+"orgacc/updOrgAccByReleCode.do",
		    				      data : $.extend(paramJSON,{
		    				    	  h5Demo_code:'dudu',
		    				    	  ext_orgReleCode:unionCode,
		    				    	  ext_orgPhone:telephone
		    				      }),
		    				      success:function(data){
		    				    	  console.log('updOrgAccByReleCode=='+JSON.stringify(data));
		    				    	  if(data.result==='0'){
		    				    		  sessionStorage.setItem('parameter',JSON.stringify(paramJSON));
		    				    		  if(data.status==='0001'){//可能需要合并账户
		    			                      if(containsCurrentApp(data.data,paramJSON.cust_account)){
		    			  	    		    	new UserPrompt('不存在可合并的账户');
		    			  	    		    	return;
		    			                      }else{
		    			    	                  transformCache(data.data);
		    			    		    		  location.assign('choose.html');  
		    			                      }                    
		    				    		  }else if(data.status==='0000'){
		    				    		    	new UserPrompt('不存在匹配的关联码');
		    				    		    	return;
		    				    		  }	    		  
		    				    	  }else{
		    						        new UserPrompt(data.discripe||data.describe);
		    				    	  }    	  
		    				      },
		    				      error:function(data){
		    				    	  if(data&&data.describe)
		    					        new UserPrompt(data.describe);
		    				      }
		    				    });
		    		  }else if(data.status==='0000'){//不存在可合并账户，询问客户是否保存手机号和账户关联码
	    				accountPrompt();
	    		    	return;
		    		  }	    		  
		    	  }else{
				        new UserPrompt(data.discripe||data.describe);
		    	  }    	  
		      },
		      error:function(data){
		    	  if(data&&data.describe)
			        new UserPrompt(data.describe);
		      }
		    });
	  }),
	  code=$('#sendCaptcha');
	  var showHeader=paramJSON.showHeader||'1';//不传默认展示标题栏
	  if(showHeader==='1'){  
		  $('#header').css('display','block'); 
		  $('#context').css('margin-top','60px'); 
	  }
	  $('#relcode').text((paramJSON.appname||'')+"账户关联码：");
	  $('#code').attr('placeholder',(paramJSON.appname||'')+'关联时的认证码').val(paramJSON.ext_orgReleCode||'').focus();
	  $('#telephone').val(paramJSON.ext_orgPhone||'');
	  var timerid;
	  code.on('click', function() {
		if(timerid)
			return;
	    var telephone = telephoneElem.val(),result,times;
	    if (telephone==='') {
	    	new UserPrompt('请输入手机号码');
	        return;
	    }
	    result=utils.checkTelephoneNumber(telephone);
	    if (!result.success) {
	    	new UserPrompt(result.msg);
	        return;
	    }
        code.attr('disabled', true);
	    $.ajax({
	      type : "get",
	      dataType : "jsonp",
	      url : base+"plugins/v4/getCode.do",
	      async : true,
	      data : {
	        'phone' : telephone,
	        'appid':paramJSON.app_key
	      },
	      success : function(data) {
	    	  if(data.result==='0'){
		          code.text((times = 60) + '秒');
		          timerid = setInterval(function() {
		            if (times == 1) {
		              if(timerid)
		                clearInterval(timerid);
		              timerid=null;
		              code.text('发送验证码');
		              code.attr('disabled', false);
		            }else
		              code.text(--times + '秒');
		          }, 1000);
		          smscode.focus();
	    	  }else{
	    		  if(data&&data.discripe)
	 			     new UserPrompt(data.discripe);
	    	  }
	      },
	      error:function(data){
	    	  if(data&&data.discripe)
			     new UserPrompt(data.discripe);
	      }
	    });
	  });	  
});